package example.service;

import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.util.Date;
import java.util.Random;

/**
 * @author lv
 * @date 2021/5/23 14:35
 */
@Service
public class OrderService {
    @Autowired
    DataSource dataSource;

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Transactional(rollbackFor=Exception.class)
    @ShardingTransactionType(TransactionType.LOCAL)  // 支持TransactionType.LOCAL, TransactionType.XA, TransactionType.BASE
    public void insert() throws Exception{

        Long order_id = new Date().getTime();
        int user_id =  new Random().nextInt(10);
        //jdbcTemplate.execute(" insert into t_order(shop_id,user_id,num,amount,order_id,status)value('123456',"+user_id+",10,1000,"+order_id+",1)",(PreparedStatementCallback<Object>) ps -> {
        jdbcTemplate.execute(" insert into t_order(shop_id,user_id,num,amount,order_id,status)value('123456',?,10,1000,?,1)",(PreparedStatementCallback<Object>) ps -> {
            ps.setInt(1, user_id);
            ps.setLong(2, order_id);
            ps.executeUpdate();
            return ps;
        });
        jdbcTemplate.execute(" insert into t_order(shop_id,user_id,num,amount,order_id,status)value('123456',?,10,1000,?,1)",(PreparedStatementCallback<Object>) ps -> {
            ps.setInt(1, user_id+1);
            ps.setLong(2, order_id);
            ps.executeUpdate();
            return ps;
        });

        System.out.println(order_id);
        throw  new Exception("报错回滚");
    }
}
